import {
  View,
  Text,
  Image,
  StyleSheet,
  Dimensions,
  SafeAreaView,
  StatusBar,
  ActivityIndicator,
  useColorScheme,
  Pressable,
  ScrollView, Alert, Platform,
  ToastAndroid,
} from 'react-native';
import React, {useState, useEffect, useRef, useCallback} from 'react';
import Video, { VideoRef } from 'react-native-video';
import PagerView from 'react-native-pager-view';
import {useFocusEffect, useScrollToTop} from '@react-navigation/native';
import ImageViewing from 'react-native-image-viewing';
import RNFS from 'react-native-fs';
import {request, PERMISSIONS, RESULTS} from 'react-native-permissions';
import * as ImagePicker from 'react-native-image-picker';
import Clipboard from '@react-native-clipboard/clipboard';

// 定义 NoteDetail 类型
interface NoteDetail {
  title: string;
  description: string;
  author: string;
  views: number;
  hasVideo: boolean;
  videoUrl: string;
  imageUrls: string[];
}

// 定义 Props 类型
interface Props {
  noteId: string;
}

// 定义 fetchData 的返回值类型
const fetchData = async (): Promise<NoteDetail | null> => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000));

    return {
      title: '夏日海边旅行必备好物分享',
      description: `
      夏天到了，去海边玩怎么能少得了这些神器呢！分享一些让你在海边游刃有余的好物。
      1. 舒适的船套：船套是旅行中不可或缺的一部分，它可以让你在水中保持舒适的温度和湿度。
      选择舒适的船套非常重要，要根据自己的身体状况和需求来选择。
      比如，如果你是一个喜欢在海边游泳的人，那么选择一个可以提供足够的浮力的船套是非常重要的。
      如果你是一个喜欢在海边潜水的人，那么选择一个可以提供足够的浮力和水下呼吸的船套是非常重要的。
      2. 舒适的脚套：脚套是旅行中不可或缺的一部分，它可以让你在水中保持舒适的温度和湿度。
      选择舒适的脚套非常重要，要根据自己的身体状况和需求来选择。
      比如，如果你是一个喜欢在海边游泳的人，那么选择一个可以提供足够的浮力的脚套是非常重要的。
      如果你是一个喜欢在海边潜水的人，那么选择一个可以提供足够的浮力和水下呼吸的脚套是非常重要的。
      3. 舒适的脚套：脚套是旅行中不可或缺的一部分，它可以让你在水中保持舒适的温度和湿度。                          
      选择舒适的脚套非常重要，要根据自己的身体状况和需求来选择。
      比如，如果你是一个喜欢在海边游泳的人，那么选择一个可以提供足够的浮力的脚套是非常重要的。
      如果你是一个喜欢在海边潜水的人，那么选择一个可以提供足够的浮力和水下呼吸的脚套是非常重要的。
      4. 舒适的脚套：脚套是旅行中不可或缺的一部分，它可以让你在水中保持舒适的温度和湿度。
      `,
      author: '旅行达人小明',
      views: 12345,
      hasVideo: true,
      videoUrl:
        'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4',
      imageUrls: [
        'https://picsum.photos/800/1200?random=1',
        'https://picsum.photos/800/1200?random=2',
        'https://picsum.photos/800/1200?random=3',
        'https://picsum.photos/800/1200?random=4',
      ],
    };
  } catch (error) {
    console.error('Error fetching note:', error);
    return null;
  }
};

const {width: screenWidth} = Dimensions.get('window');

const NoteDetailScreen: React.FC<Props> = ({noteId}) => {
  const [note, setNote] = useState<NoteDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeSlide, setActiveSlide] = useState(0);
  const [isPlaying, setIsPlaying] = useState(true); // 视频播放状态
  const [isImageViewerVisible, setImageViewerVisible] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  const pagerRef = useRef<PagerView>(null);
  const videoRef = useRef<VideoRef>(null); // 视频组件引用
  const scrollViewRef = useRef<ScrollView>(null);

  const showToast = (message: string) => {
    ToastAndroid.show(message, ToastAndroid.SHORT);
  };

  // 模拟数据加载
  useEffect(() => {
    const loadNote = async () => {
      const fetchedNote = await fetchData();
      setNote(fetchedNote);
      setLoading(false);
    };

    loadNote();
  }, []);

  // 监听屏幕焦点变化
  useFocusEffect(
    useCallback(() => {
      // 屏幕获得焦点时
      if (videoRef.current && note?.hasVideo && activeSlide === 0) {
        setIsPlaying(true);
      }

      // 屏幕失去焦点时
      return () => {
        if (videoRef.current) {
          videoRef.current.pause();
          setIsPlaying(false);
        }
      };
    }, [activeSlide, note]),
  );

  const handleImagePress = (index: number) => {
    setCurrentImageIndex(index);
    setImageViewerVisible(true);
  };

  const saveImageToGallery = async (imageUrl: string) => {
    try {
      const permission = await request(
        Platform.OS === 'android'
          ? PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE
          : PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY,
      );

      if (permission === RESULTS.GRANTED) {
        // 生成当前时间戳
        const timestamp = Date.now();
        const fileName = `${timestamp}.jpg`;
        const path = `${RNFS.DocumentDirectoryPath}/${fileName}`;

        // 下载图片
        const download = await RNFS.downloadFile({
          fromUrl: imageUrl,
          toFile: path,
        }).promise;

        if (download.statusCode === 200) {
          if (Platform.OS === 'android') {
            // Android 保存到相册
            await RNFS.copyFile(path, `${RNFS.ExternalStorageDirectoryPath}/Pictures/${fileName}`);
            ToastAndroid.show('图片已保存到相册', ToastAndroid.SHORT);
          } else if (Platform.OS === 'ios') {
            // iOS 保存到相册
            const { saveImageToCameraRoll } = ImagePicker;
            await saveImageToCameraRoll(path);
            ToastAndroid.show('图片已保存到相册', ToastAndroid.SHORT);
          }
        } else {
          Alert.alert('保存失败', '无法下载图片');
        }
      } else {
        Alert.alert('权限不足', '请授予存储权限以保存图片');
      }
    } catch (error) {
      console.error('保存图片失败:', error);
      ToastAndroid.show('发生错误，无法保存图片', ToastAndroid.SHORT);
    }
  };

  // 轮播页切换时控制视频播放
  const handlePageSelected = (e: {nativeEvent: {position: number}}) => {
    const position = e.nativeEvent.position;
    setActiveSlide(position);

    if (videoRef.current) {
      if (note?.hasVideo && position === 0) {
        // 如果切换到视频页且有视频，播放视频
        setIsPlaying(true);
      } else {
        // 如果切换到图片页，暂停视频
        setIsPlaying(false);
      }
    }
  };

  // 获取当前主题的颜色
  const getThemeColors = () => {
    return isDarkMode
      ? {
          background: '#121212',
          textPrimary: '#FFFFFF',
          textSecondary: '#AAAAAA',
          card: '#1E1E1E',
        }
      : {
          background: '#FFFFFF',
          textPrimary: '#000000',
          textSecondary: '#666666',
          card: '#F5F5F5',
        };
  };

  if (loading) {
    return (
      <SafeAreaView
        style={[
          styles.container,
          {backgroundColor: isDarkMode ? '#121212' : '#FFFFFF'},
        ]}>
        <ActivityIndicator size="large" color="#E4405F" />
      </SafeAreaView>
    );
  }

  if (!note) {
    return (
      <SafeAreaView
        style={[
          styles.container,
          {backgroundColor: isDarkMode ? '#121212' : '#FFFFFF'},
        ]}>
        <Text
          style={[
            styles.errorText,
            {color: isDarkMode ? '#FFFFFF' : '#000000'},
          ]}>
          笔记加载失败
        </Text>
      </SafeAreaView>
    );
  }

  const {background, textPrimary, textSecondary, card} = getThemeColors();
  const totalSlides = note.hasVideo
    ? note.imageUrls.length
    : note.imageUrls.length;

    const handleSharePress = () => {
      // 复制字符串到剪切板
      let shareLink = 'ctn://note/' + noteId + '\n复制上面链接在浏览器中打开';
      Clipboard.setString(shareLink);
      showToast('分享链接已复制到剪切板');
    }

  return (
    <SafeAreaView style={[styles.container, {backgroundColor: background}]}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={isDarkMode ? '#121212' : '#FFFFFF'}
      />

      {/* 轮播图区域 */}
      <View style={styles.carouselContainer}>
        <PagerView
          ref={pagerRef}
          style={styles.pagerView}
          initialPage={0}
          onPageSelected={handlePageSelected} // 添加页面切换回调
          showPageIndicator={false}>
          {note.imageUrls.map((url, index) => (
            <View key={url} style={styles.carouselItem}>
              {note.hasVideo && index === 0 ? (
                <Video
                  ref={videoRef}
                  source={{uri: note.videoUrl}}
                  style={styles.video}
                  resizeMode="cover"
                  controls={isPlaying}
                  paused={!isPlaying}
                  repeat
                />
              ) : (
                <Pressable key={url} onPress={() => handleImagePress(index)}>
                  <Image
                    source={{uri: url}}
                    style={styles.image}
                    resizeMode="cover"
                  />
                </Pressable>
              )}
            </View>
          ))}
        </PagerView>

        {/* 图片查看器 */}
        <ImageViewing
          images={note.imageUrls.map((url) => ({ uri: url }))}
          imageIndex={currentImageIndex}
          visible={isImageViewerVisible}
          onRequestClose={() => setImageViewerVisible(false)}
          FooterComponent={({ imageIndex }) => (
            <Pressable
              style={styles.saveButton}
              onPress={() => saveImageToGallery(note.imageUrls[imageIndex])}
            >
              <Text style={styles.saveButtonText}>保存到相册</Text>
            </Pressable>
          )}
        />

        {/* 轮播指示器 */}
        <View style={styles.indicatorContainer}>
          {Array(totalSlides)
            .fill(0)
            .map((_, i) => (
              <View
                key={i}
                style={[
                  styles.indicatorDot,
                  {
                    backgroundColor:
                      i === activeSlide
                        ? '#FFFFFF'
                        : 'rgba(255, 255, 255, 0.5)',
                    width: i === activeSlide ? 12 : 6,
                  },
                ]}
              />
            ))}
        </View>
      </View>

      {/* 内容区域 */}
      <ScrollView
        ref={scrollViewRef}
        style={styles.contentContainer}
        showsVerticalScrollIndicator={false}>
        <View style={[styles.card, {backgroundColor: card}]}>
          {/* 标题 */}
          <Text style={[styles.title, {color: textPrimary}]}>{note.title}</Text>

          {/* 作者信息 */}
          <View style={styles.authorContainer}>
            <Image
              source={{uri: 'https://picsum.photos/100/100?random=author'}}
              style={styles.avatar}
              resizeMode="cover"
            />
            <View style={styles.authorInfo}>
              <Text style={[styles.authorName, {color: textPrimary}]}>
                {note.author}
              </Text>
              <Text style={[styles.views, {color: textSecondary}]}>
                {note.views.toLocaleString()} 次浏览
              </Text>
            </View>
            <Pressable style={styles.followButton} onPress={handleSharePress}>
              <Text style={styles.followText}>分享</Text>
            </Pressable>
          </View>

          {/* 分割线 */}
          <View
            style={[
              styles.divider,
              {borderColor: isDarkMode ? '#333333' : '#EEEEEE'},
            ]}
          />

          {/* 描述内容 */}
          <Text style={[styles.description, {color: textPrimary}]}>
            {note.description}
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  carouselContainer: {
    width: '100%',
    height: screenWidth,
    backgroundColor: '#000000',
  },
  pagerView: {
    flex: 1,
  },
  carouselItem: {
    width: screenWidth,
    height: screenWidth,
  },
  image: {
    width: '100%',
    height: '100%',
  },
  video: {
    width: '100%',
    height: '100%',
  },
  playIconContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  indicatorContainer: {
    position: 'absolute',
    bottom: 16,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 4,
  },
  indicatorDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
    transitionDuration: '200ms',
  },
  contentContainer: {
    flex: 1,
    padding: 16,
    // 增加 marginTop 值，避免遮挡图片
    marginTop: 16,
    backgroundColor: 'transparent',
  },
  card: {
    borderRadius: 16,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    // 将圆角移到 card 样式中
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  authorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 12,
  },
  authorInfo: {
    flex: 1,
  },
  authorName: {
    fontSize: 16,
    fontWeight: '500',
  },
  views: {
    fontSize: 12,
  },
  followButton: {
    backgroundColor: '#E4405F',
    borderRadius: 20,
    paddingVertical: 8,
    paddingHorizontal: 16,
  },
  followText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '500',
  },
  divider: {
    borderWidth: 0.5,
    marginVertical: 12,
  },
  description: {
    fontSize: 16,
    lineHeight: 24,
  },
  errorText: {
    fontSize: 18,
    textAlign: 'center',
    padding: 20,
  },
  saveButton: {
    backgroundColor: '#E4405F',
    padding: 10,
    borderRadius: 5,
    alignItems: 'center',
    margin: 10,
  },
  saveButtonText: {
    color: '#fff',
    fontSize: 16,
  },
});

export default NoteDetailScreen;
